import type { BlockProcessor, PreBlock, TextDoc, Row, ContainerProcessor } from './types';

import codeBlock from './blocks/code-block';
import atxHeadingBlock from './blocks/atx-heading';
import fencedCodeBlock from './blocks/fenced-code-block';
import horizentalRule from './blocks/horizental-rule';
import paragraphBlock from './blocks/paragraph';
import setextHeading from './blocks/setext-heading';

import blockquote from './containers/blockquote';

function docToTree(
  doc: TextDoc,
  blockProcessors: BlockProcessor[],
  containerProcessors: ContainerProcessor[]
): PreBlock[] {
  let pbs: PreBlock[] = doc.rows;
  for (const containerProcessor of containerProcessors) {
    pbs = containerProcessor.process(pbs);
  }
  for (const blockProcessor of blockProcessors) {
    pbs = blockProcessor.process(pbs);
  }
  return pbs;
}

function parse(doc: TextDoc) {
  const blocks = [
    fencedCodeBlock.processor,
    codeBlock.processor,
    atxHeadingBlock.processor,
    setextHeading.processor,
    horizentalRule.processor,
    paragraphBlock.processor,
  ];
  const containers = [blockquote.makeProcessor(blocks)];
  return docToTree(doc, blocks, containers);
}

export default {
  parse,
};
